<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-28
 * Time: 18:52
 */

namespace app\api\service\order;


use app\api\controller\v1\PayMoney;
use app\api\model\CouponUser;
use app\api\model\ProductOrder;
use app\api\model\ProductOrderContent;
use app\api\model\ProductOrderCouponUse;
use app\api\model\StoreUser;
use app\api\model\StoreUserItem;
use app\api\model\TeamUser;
use app\api\model\User;
use app\api\model\UserInvitation;
use app\api\model\UserMoney;
use app\api\model\UserTiMoneyOrder;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\facade\Log;

class ProductOrderSer
{
    // 订单
    private $order;

    // 用户信息
    private $user;

    function __construct($order)
    {
        $this->order = $order;
        $this->user = User::get($this->order['user_id']);
    }


    /**
     * 更改用户状态
     */
    public function changeStatus()
    {
        if($this->order['status'] == 1) {
            Db::startTrans();
            try
            {
                // 更新订单状态
                $this->updateOrder();
                Db::commit();
                return true;
            }
            catch (Exception $ex)
            {
                Db::rollback();
                throw $ex;
                return true;
//                file_put_contents('/www/wwwroot/digcusmark.com/shuzi-cms/pay_xml.txt', '支付时间:' . date('Y-m-d H:i:s') . json_encode($ex), FILE_APPEND);

            }
        } else {
            return true;
        }
    }

    /**
     * 更新状态
     */
    private function updateOrder()
    {
        $productOrder = new ProductOrder();
        $productOrder->save([
            'status' => 2,
            'pay_time' => time(),
        ],['id' => $this->order['id']]);
        $productOrderContent = new ProductOrderContent();
        $productOrderContent->save([
            'status' => 2
        ], [ 'product_order_id'=> $this->order['id']]);
        if(!$this->user['store_id'] && $this->user['type'] == 1) {
            User::where('id',$this->user['id'])->update([
                'store_id' => $this->order['store_id']
            ]);
        }
        // 生成订单二维码
        $token = new Token();
        $token->setCode($this->order['id']);
        if($this->order['order_type'] == 1) {
            $this->addCoupon();
            $this->minCoupon();
            $this->addInviteMoney();
        } else {
            $this->addInviteMoneyOne();
        }
    }

    private function minCoupon()
    {
        if($this->order['coupon_id'] > 0) {
            ProductOrderCouponUse::create([
                'coupon_user_id' => $this->order['coupon_id'],
                'product_order_id' => $this->order['id'],
                'price' => $this->order['coupon_money'],
                'user_id' => $this->user['id']
            ]);
        }
    }


    /**
     * 返优惠券
     */
    private function addCoupon()
    {
        $productOrderContent = ProductOrderContent::with('product.coupon')->where('product_order_id',$this->order['id'])
            ->find();
        if($productOrderContent['product']['coupon_status'] == 1) {
            if($this->order['actual_price'] >= $productOrderContent['product']['coupon']['amount_of_money']) {
                CouponUser::create([
                    'coupon_name' => $productOrderContent['product']['coupon']['name'],
                    'usage_times' => $productOrderContent['product']['coupon']['usage_times'],
                    'surplus_times' => $productOrderContent['product']['coupon']['usage_times'],
                    'start_time' => $productOrderContent['product']['coupon']['start_time'],
                    'end_time' => $productOrderContent['product']['coupon']['end_time'],
                    'amount_of_money_use' => $productOrderContent['product']['coupon']['amount_of_money_use'],
                    'money' => $productOrderContent['product']['coupon']['money'],
                    'user_id' => $this->user['id'],
                    'coupon_msg' => json_encode($productOrderContent['product']['coupon'])
                ]);
            }
        }
    }

    // 专属卡给团员返佣
    public function addInviteMoneyOne()
    {
        $productOrderContent = ProductOrderContent::with('product')->where('product_order_id',$this->order['id'])
            ->find();
        if($productOrderContent['product']['product_type'] == 2) {
            $end_time =  time()+ ($productOrderContent['product']['end_time']*86400);
            ProductOrderContent::where('id',$this->order['id'])->update([
                'product_start_time' => time(),
                'product_end_time' => $end_time
            ]);
            $money = $productOrderContent['product']['group_invite_cash'];
            if($money > 0) {
                $teamUser = TeamUser::where('id',$this->order['order_team_user_id'])->with('user')->find();
                User::where('id',$teamUser['user_id'])->setDec('money',$money);
                UserMoney::create([
                    'order_id' => $this->order['id'],
                    'user_id' => $this->user['id'],
                    'user_type' => 1,
                    'type' => 1,
                    'user_money' => $teamUser['user']['money'],
                    'money' => $money,
                    'status' => 4
                ]);
            }
        }
    }

    /**
     * 给上级返佣
     *      1.上级是顾客(必须是购买产品后)
     *          1. 第一次下单
     *              1. 给老用户返现
     *              2. 给新顾客和老顾客返优惠券
     *      2.上级是员工
     *          1. 给员工返现
     *      3.上级是团员
     *          1. 给团员返现
     *      4.下单满了以后给返优惠券
     *      5.返佣只计算一个
     */
    private function addInviteMoney()
    {
        $UserInvitation = UserInvitation::where('invitee',$this->user['id'])->find();
        $productOrderContent = ProductOrderContent::with('product.coupon')
            ->where('product_order_id',$this->order['id'])
            ->find();
        $total = 0;
        if($UserInvitation['type'] == 1) {
            // 给老顾客返现
            $oldUser = User::get($UserInvitation['inviter']);
            if($oldUser) {
                $order_count = ProductOrder::where('user_id',$this->order['user_id'])
                    ->where('status','gt',1)->count();
                if($order_count == 1) {
                    $money = $productOrderContent['product']['new_user_invite_cash'];
                    $total += $money;
                    // 给老用户返现
                    User::where('id',$oldUser['id'])
                        ->setInc('money',$money);
                    UserMoney::create([
                        'order_id' => $this->order['id'],
                        'user_id' => $oldUser['id'],
                        'user_type' => 1,
                        'type' => 1,
                        'user_money' => $oldUser['money'],
                        'money' => $money,
                        'status' => 2
                    ]);
                    UserTiMoneyOrder::create([
                        'user_id' => $oldUser['id'],
                        'money' => $money,
                        'order_id' => $this->order['id'],
                        'order_no' => 'm'.$this->order['out_trade_no'],
                        'status' => 1,
                        'product_name' => $productOrderContent['product']['name']
                    ]);
                    $payMoney = new PayMoney();
                    $payMoney->addUserMoney('m'.$this->order['out_trade_no']);
                    // 给新老用户返优惠券
                    if($productOrderContent['product']['coupon']) {
                        CouponUser::create([
                            'coupon_name' => $productOrderContent['product']['coupon']['name'],
                            'usage_times' => $productOrderContent['product']['coupon']['usage_times'],
                            'surplus_times' => $productOrderContent['product']['coupon']['usage_times'],
                            'start_time' => $productOrderContent['product']['coupon']['start_time'],
                            'end_time' => $productOrderContent['product']['coupon']['end_time'],
                            'amount_of_money_use' => $productOrderContent['product']['coupon']['amount_of_money_use'],
                            'money' => $productOrderContent['product']['coupon']['money'],
                            'user_id' => $this->user['id'],
                            'coupon_msg' => json_encode($productOrderContent['product']['coupon'])
                        ]);
                        CouponUser::create([
                            'coupon_name' => $productOrderContent['product']['coupon']['name'],
                            'usage_times' => $productOrderContent['product']['coupon']['usage_times'],
                            'surplus_times' => $productOrderContent['product']['coupon']['usage_times'],
                            'start_time' => $productOrderContent['product']['coupon']['start_time'],
                            'end_time' => $productOrderContent['product']['coupon']['end_time'],
                            'amount_of_money_use' => $productOrderContent['product']['coupon']['amount_of_money_use'],
                            'money' => $productOrderContent['product']['coupon']['money'],
                            'user_id' => $oldUser['id'],
                            'coupon_msg' => json_encode($productOrderContent['product']['coupon'])
                        ]);
                    }
                }
            }
        }elseif($UserInvitation['type'] == 2){
            $order_count = ProductOrder::where('user_id',$this->order['user_id'])
                ->where('status','gt',1)->count();
            if($order_count == 1) {
                // 给员工返现
                $StoreUser = StoreUser::get($UserInvitation['inviter']);
                $userInfo = User::get($StoreUser['user_id']);
                $money = $productOrderContent['product']['invite_cash'];
                if($money > 0) {
                    $total += $money;
                    User::where('id', $userInfo['id'])
                        ->setInc('money', $money);
                    UserMoney::create([
                        'order_id' => $this->order['id'],
                        'user_id' => $userInfo['id'],
                        'store_user_id' => $StoreUser['id'],
                        'user_type' => 2,
                        'type' => 1,
                        'user_money' => $userInfo['money'],
                        'money' => $money,
                        'status' => 2
                    ]);
                }
            } elseif($order_count > 1){
                $StoreUser = StoreUser::get($UserInvitation['inviter']);
                $userInfo = User::get($StoreUser['user_id']);
                $money = $productOrderContent['product']['invite_cash_two'];
                if($money > 0) {
                    $total += $money;
                    User::where('id', $userInfo['id'])
                        ->setInc('money', $money);
                    UserMoney::create([
                        'order_id' => $this->order['id'],
                        'user_id' => $userInfo['id'],
                        'store_user_id' => $StoreUser['id'],
                        'user_type' => 2,
                        'type' => 1,
                        'user_money' => $userInfo['money'],
                        'money' => $money,
                        'status' => 2
                    ]);
                }
            }
        } elseif($UserInvitation['type'] == 3){
            $order_count = ProductOrder::where('user_id',$this->order['user_id'])
                ->where('status','gt',1)->count();
            if($order_count == 1) {
                // 给团员返现
                $TeamUser = TeamUser::get($UserInvitation['inviter']);
                $userInfo = User::get($TeamUser['user_id']);
                $money = $productOrderContent['product']['group_invite_cash'];
                $total += $money;
                User::where('id', $userInfo['id'])
                    ->setInc('money', $money);
                UserMoney::create([
                    'order_id' => $this->order['id'],
                    'user_id' => $userInfo['id'],
                    'team_user_id' => $TeamUser['id'],
                    'user_type' => 3,
                    'type' => 1,
                    'user_money' => $userInfo['money'],
                    'money' => $money,
                    'status' => 2
                ]);
            }
        }
        //  给老板返佣，有一种情况就是 他下级买了产品，得到了他自己的返佣。还有他老板的返佣
        $moneyOne = $productOrderContent['product']['boss_cash'];
        $storeUserItem = StoreUserItem::where('store_id',$this->order['store_id'])->find();
        $StoreUserOne = StoreUser::get($storeUserItem['store_user_id']);
        $userInfoOne = User::get($StoreUserOne['user_id']);
        if($moneyOne > 0 && $userInfoOne) {
            $total += $moneyOne;
            User::where('id', $userInfoOne['id'])
                ->setInc('money', $moneyOne);
            UserMoney::create([
                'order_id' => $this->order['id'],
                'user_id' => $userInfoOne['id'],
                'store_user_id' => $StoreUserOne['id'],
                'user_type' => 2,
                'type' => 1,
                'user_money' => $userInfoOne['money'],
                'money' => $moneyOne,
                'status' => 2
            ]);
            UserTiMoneyOrder::create([
                'user_id' => $userInfoOne['id'],
                'money' => $moneyOne,
                'order_id' => $this->order['id'],
                'order_no' => 'm'.$this->order['out_trade_no'],
                'status' => 1,
                'product_name' => $productOrderContent['product']['name']
            ]);
        }
        ProductOrder::where('id',$this->order['id'])->update([
            'invitation_money' => $total
        ]);
    }
}